//
//  NSObject+Model.m
//  Objective-C
//
//  Created by S_Line on 2018/5/8.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "NSObject+Model.h"

#import <objc/runtime.h>

@implementation NSObject (Model)

+ (instancetype)modelWithDict:(NSDictionary *)dict {
    
    id objc = [[self alloc] init];
    
    Class class = self;
    
    do {
        unsigned int count;
        
        Ivar *ivarList = class_copyIvarList(class, &count);
        
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivarList[i];
            
            NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
            NSString *key = [ivarName substringFromIndex:1];
            NSString *ivarTypeStr = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
            ivarTypeStr = [ivarTypeStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            ivarTypeStr = [ivarTypeStr stringByReplacingOccurrencesOfString:@"@" withString:@""];
            
            id value = dict[key];
            if (value && [value isKindOfClass:[NSDictionary class]] && ![ivarTypeStr hasPrefix:@"NS"]) {
                Class ivarClass = NSClassFromString(ivarTypeStr);
                
                value = [ivarClass modelWithDict:value];
            }
            
            if (value) {
                [objc setValue:value forKey:key];
            }
        }
        
        class = [class superclass];
        
        free(ivarList);
        
    } while (![NSStringFromClass(class) isEqualToString:NSStringFromClass([NSObject class])]);
    
    
    return objc;
}

@end
